﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace PowerManager.Framework.DataPresentation.UpdateStrategy
{
    class TimingUpdate:IUpdateStrategy
    {
        // Default 15 minitues update interval.
        private TimeSpan _updateInterval = new TimeSpan(0, 15, 0);
        private Timer _timer;

        public TimingUpdate(TimeSpan updateInterval) {
            _updateInterval = updateInterval;
        }

        public TimeSpan UpdateInterval {
            get { return _updateInterval; }
            set { _updateInterval = value; }
        }
        
        public event EventHandler UpdateAction;
        public void OnUpdateAction(EventArgs e) {
            var handle = Interlocked.CompareExchange(ref UpdateAction, null, null);
            if (handle != null) {
                handle(this, null);
            }
        }

        public void ExecuteStrategy() {
            _timer = new Timer(CallbackLoop, null, 0, Timeout.Infinite);
        }

        private void CallbackLoop(Object state) {
            OnUpdateAction(null);
            _timer.Change(_updateInterval, TimeSpan.FromMilliseconds(-1));
        }
    }
}
